import os
import logging

from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_mail import Mail

from src.api_server.page import page
from src.api_server.verification import verification
from src.db_models.base import db
from src.api_server.route import api

load_dotenv()

app = Flask(__name__)  # template_folder='templates'
CORS(app)

app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET')

jwt = JWTManager(app)  # 初始化 JWTManager

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)  # 绑定应用到 SQLAlchemy 实例

app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER')
app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS')
app.config['MAIL_PORT'] = os.environ.get('MAIL_PORT')
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
mail = Mail(app)

# Register the blueprint
app.register_blueprint(api)
app.register_blueprint(page)
app.register_blueprint(verification)

# 为什么是放在这里？？？而不是main中？
with app.app_context():
    try:
        print("Attempting to create tables...")
        db.create_all()  # 尝试创建所有表
        tables = db.inspect(db.engine).get_table_names()  # 获取所有表名
        print(f"Existing tables: {tables}")
    except Exception as e:
        print(f"Error creating tables: {e}")

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    app.run(debug=True)